package com.example.video.controller;

import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.example.video.common.Result;
import com.example.video.entity.Account;
import com.example.video.entity.AdminShowVideo;
import com.example.video.entity.Platform;
import com.example.video.entity.Video;
import com.example.video.service.IAccountService;
import com.example.video.service.IPlatformService;
import com.example.video.service.IVideoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author qiusuyang
 * @since 2024-04-13
 */
@Slf4j
@RestController
@RequestMapping("/video")
public class VideoController {

    @Resource
    private IVideoService videoService;

    @Resource
    private IPlatformService platformService;

    @Resource
    private IAccountService accountService;

    /**
     * 通过源作者模糊查询相关视频信息
     * @param page
     * @param limit
     * @param name
     * @return
     */

    @PostMapping("/videoSearch")
    public Result<List<AdminShowVideo>> searchVideo(Integer page, Integer limit,
                                                    @RequestParam(defaultValue = "") String name,
                                                    @RequestParam(defaultValue = "") String platformName,

                                                    @RequestParam(defaultValue = "0")Integer status
    ){
//        log.info("ApiController -> videoSearch -> msg : status = "+status );
        // 创建 SimpleDateFormat 对象，指定日期格式
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Result<List<AdminShowVideo>> rs = new Result<>();
        List<AdminShowVideo> rsList = new ArrayList<>();

        Integer platformid = 0;
        if( !"".equals(platformName)){
            Platform platform = platformService.getItemByName(platformName);
            if(platform != null){
                platformid = platform.getId();
            }else{
                rs.setMsg("无此平台！");
                rs.setCode(-1);
                rs.setData(null);
                return rs;
            }
        }

        // 5.7 修改，数据库进行分页，不手动分页
        List<Account> accounts = accountService.searchByNameAndplatformId(name, platformid);
        List<Integer> accountIdList = new ArrayList<>();
        for (Account temp : accounts) {
            accountIdList.add(temp.getId());
        }
//        log.info("ApiController -> videoSearch -> msg : account = "+accounts);
        if ( accounts.isEmpty() ){
            rs.setMsg("无数据！");
            rs.setCode(-1);
            rs.setCount(0);
            rs.setData(null);
        }else{
            List<Video> videos = videoService.getListByAccountIdAndStatus(page, limit, accountIdList, status);
            for ( Video item:videos ){
                Account targetAccount = null;
                for (Account account : accounts) {
                    if (account.getId().equals(item.getAccountId())) {
                        targetAccount = account;
                        break;
                    }
                }
//                log.info("ApiController -> searchVideo -> msg: search account = "+targetAccount);
                AdminShowVideo temp = new AdminShowVideo();
                temp.setId(item.getId());
                temp.setTitle(item.getTitle());
                temp.setResourceId(item.getResourceId());
                if( item.getCreateTime() == null){
                    temp.setCreateTime(null);
                }else{
                    temp.setCreateTime(dateFormat.format(item.getCreateTime()));
                }
                temp.setStatus(item.getStatus());
                temp.setMedias(item.getMedias());
                temp.setUserId(targetAccount.getId());
                temp.setUserName(targetAccount.getName());
                temp.setErrMsg(item.getErrMsg());
                // 6.18 添加设置错误平台
                temp.setPublishErr(item.getPublishErr());
                rsList.add(temp);
            }
            rs.setCount(videoService.getCountByAccountIdAndDownLoading( accountIdList, status));
            rs.setData(rsList);
            rs.setCode(0);
            rs.setMsg("获取成功！");

        }
        return rs;
    }


    /**
     * @desc 通过ID获取账户项信息
     * @param id 账户项的ID，用于查询特定的账户项
     * @return 返回一个Result对象，其中包含账户项信息和操作结果的状态码、消息
     */

    @PostMapping("/videoItem")
    public Result<Video> getVideoItem(Integer id){
        Result<Video> rs = new Result<>();
        Video item = videoService.getItem(id);
        if(item != null){
            rs.setData(item);
            rs.setMsg("获取成功！");
            rs.setCode(0);
        }else {
            rs.setCode(-1);
            rs.setData(null);
            rs.setMsg("获取失败！");
        }
        rs.setCount(0);
        return rs;
    }



    /**
     * @param item 修改或添加的信息
     * @return 是否成功
     */
    @ResponseBody
    @PostMapping("/save")
    public Result<Boolean> saveItem(Video item)
    {
        Result<Boolean> rs = new Result<>();

        Boolean flag = videoService.save(item);
        rs.setData(flag);
        if (flag) {
            rs.setCode(200);
            rs.setMsg("成功");
        } else {
            rs.setCode(500);
            rs.setMsg("失败");
        }
        return rs;
    }

    /**
     * @param id 待删除数据的id
     * @return 是否成功
     */
    @ResponseBody
    @PostMapping("/delete")
    public Result<Boolean> deleteItem(Integer id)
    {
        Result<Boolean> rs = new Result<>();
        Boolean flag = videoService.delete(id);
        rs.setData(flag);
        if (flag) {
            rs.setCode(200);
            rs.setMsg("成功");
        } else {
            rs.setCode(500);
            rs.setMsg("失败");
        }
        return rs;
    }

    @ResponseBody
    @PostMapping("/modify/title")
    public Result<Boolean> modifyTitle(Integer id, String title) {
        Result<Boolean> rs = new Result<>();
        rs.setMsg("ok");
        log.info("VideoCtr -> modify/title ->msg: 数据= "+Db.lambdaQuery(Video.class)
                .eq(Video::getId, id)
                .one()
        );
        log.info("VideoCtr -> modify/title ->msg: "+title);
        log.info("account -> modify/title ->msg: 更新 = "+Db.lambdaUpdate(Video.class)
                .eq(Video::getId, id)
                .set(Video::getTitle, title)
                .update()
        );

        return rs;
    }

}
